/**
 * 跟spring功能绑定在一起类工具类，它提供生成类实例并提供字段值注入功能
 */
package com.cnfangmao.common.util;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;

import com.cnfangmao.util.ClassUtil;
import com.cnfangmao.util.ReflectUtil;

public class ClassUtilWithAutowired {
	private static Logger logger = Logger.getLogger(ClassUtilWithAutowired.class);
	private static ConfigurableApplicationContext applicationContext;

	public static ConfigurableApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {
		ClassUtilWithAutowired.applicationContext = applicationContext;

	}

	/***
	 * 注入字段值
	 * 
	 * @param clazz
	 * @param instance
	 */
	private static <T> void injectField(Class<T> clazz, T instance) {
		if (applicationContext != null && instance != null) {
			List<Field> fields = ReflectUtil.getAnnotationFields(clazz, Autowired.class);
			for (Field field : fields) {
				Object injectedbean = applicationContext.getBean(field.getType());
				try {
					field.setAccessible(true);
					field.set(instance, injectedbean);
				} catch (Exception e) {
					logger.error(e);
				}
			}
		}
	}

	/****
	 * 获取一个类实例并注入相应字段值
	 * 
	 * @param clazz
	 * @param bCreateNew
	 * @return
	 */
	public static <T> T getInstance(Class<T> clazz, boolean bCreateNew) {
		T instance = ClassUtil.getInstance(clazz, bCreateNew);
		injectField(clazz, instance);
		return instance;
	}

	public static synchronized <T> T getInstance(Class<T> clazz, Class<?>[] parameterTypes, Object[] args) {
		T instance = ClassUtil.getInstance(clazz, parameterTypes, args);
		injectField(clazz, instance);
		return instance;
	}

}
